<template>
  <!-- 报告单元 -->
  <div id="labRptGroupPoct">
    <Breadcrumb content="报告单元" />
    <div class="bodyContent">
      <el-tabs type="border-card">
        <el-tab-pane label="基础字典">
          <Splitpanes class="area">
            <Pane size="65">
              <vxe-toolbar perfect>
                <template #buttons>
                  <vxe-input v-model="form.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @keyup="keyupEnter" @clear="findRptGroupList" @search-click="handleSearch(form)"></vxe-input>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="findRptGroupList"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-sort" content="数据同步" :loading="showLoading1" @click="pullPloyee"></vxe-button>
                </template>
              </vxe-toolbar>

              <div class="leftTable">
                <vxe-table ref="rptGroupTable" border="inner" align="left" class="mytable-scrollbar" :loading="showLoading" height="auto" :data="rptGroupList" :expand-config="{ expandAll: true, reserve: true }" @current-change="userRowClick" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
                    isArrow: true,
                    isTab: true,
                    isEdit: false
                  }" :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
                  <vxe-column type="checkbox" width="30px" align="center"></vxe-column>
                  <vxe-column field="seq" title="序号" width="35px" align="center"></vxe-column>
                  <vxe-column field="rptGroupName" title="报告单元名称" width="120px"> </vxe-column>
                  <vxe-column field="rptGroup" title="报告单元编码" width="100px"> </vxe-column>
                  <vxe-column field="businessType" title="业务类型" min-width="130px"> </vxe-column>
                  <vxe-column field="rptGroupExplain" title="报告单元说明" min-width="130px">
                  </vxe-column>
                  <vxe-column field="inputCode" title="助记码" min-width="130px"></vxe-column>
                  <vxe-column field="workGroup" title="工作组" width="120px">
                    <template #default="{ row }">
                      {{ getWorkGroupName(row) }}
                    </template>
                  </vxe-column>
                  <vxe-column field="remark1" title="报告备注1" min-width="110px"> </vxe-column>
                  <vxe-column field="remark2" title="报告备注2" min-width="110px"> </vxe-column>
                  <vxe-column field="remark3" title="报告备注3" min-width="110px"> </vxe-column>
                  <vxe-column field="enable" title="是否启用" width="80" align="center" checked-value="0" unchecked-value="1">
                    <template #default="{ row }">
                      <el-tag :type="getIsStaticTagType(row)">
                        {{ getIsStaticStatusDesc(row) }}
                      </el-tag>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>
            </Pane>

            <Pane size="35">
              <el-tabs type="border-card">
                <el-tab-pane label="基本信息">
                  <!-- 右侧基本信息 -->
                  <el-form ref="rptGroupForm" :model="form" :rules="rptGroupFormRule" class="form-input-m" v-loading="showLoading" label-width="110px" inline-message>
                    <el-form-item label="报告单元编码" prop="rptGroup">
                      <el-input v-model="form.rptGroup" placeholder="请输入报告单元编码" clearable></el-input>
                    </el-form-item>

                    <el-form-item label="报告单元名称" prop="rptGroupName">
                      <el-input v-model="form.rptGroupName" placeholder="请输入报告单元名称" clearable @change="autoInputCode"></el-input>
                    </el-form-item>

                    <el-form-item label="工作组" prop="workGroup">
                      <el-select v-model="form.workGroup" filterable placeholder="请选择工作组" style="width: 200px">
                        <el-option v-for="workGroup in workGroupList" :key="workGroup.id" :label="workGroup.name" :value="workGroup.code"></el-option>
                      </el-select>
                    </el-form-item>

                    <el-form-item label="业务类型" prop="businessType">
                      <el-radio-group v-model="form.businessType">
                        <el-radio v-for="rType in businessTypeList" :key="rType.commonId" :label="rType.code">{{rType.name}}</el-radio>
                        <!-- <el-radio label="通用">通用</el-radio>
                        <el-radio label="细菌">细菌</el-radio>
                        <el-radio label="图文">图文</el-radio>
                        <el-radio label="骨髓">骨髓</el-radio>
                        <el-radio label="导入">导入</el-radio>
                        <el-radio label="基因">基因</el-radio>
                        <el-radio label="血库">血库</el-radio> -->
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="报告单元说明" prop="businessType">
                      <el-input v-model="form.rptGroupExplain" placeholder="报告单元说明" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="助记码" prop="inputCode">
                      <el-input v-model="form.inputCode" placeholder="请输入助记码" clearable></el-input>
                    </el-form-item>

                    <el-form-item label="报告备注1" prop="remark1">
                      <el-input v-model="form.remark1" placeholder="请输入报告备注" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="报告备注2" prop="remark1">
                      <el-input v-model="form.remark2" placeholder="请输入报告备注" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="报告备注3" prop="remark1">
                      <el-input v-model="form.remark3" placeholder="请输入报告备注" clearable></el-input>
                    </el-form-item>

                    <el-form-item label="是否启用" prop="enable">
                      <el-switch v-model="form.enable" inline-prompt active-text="是" inactive-text="否" active-value="1" inactive-value="0"></el-switch>
                    </el-form-item>
                    <el-form-item prop="seq" label="顺序">
                      <el-input-number v-model="form.seq" :min="1" :max="10000" />
                    </el-form-item>

                    <el-form-item class="form-footer">
                      <template #default>
                        <el-button type="primary" @click="addrptGroup">新建</el-button>
                        <el-button type="primary" v-loading="saveLoading" @click="save('rptGroupForm')">保存</el-button>
                        <el-button type="default" @click="resetForm(currentUser)">重置</el-button>
                      </template>
                    </el-form-item>
                  </el-form>
                </el-tab-pane>

                <el-tab-pane label="报告单元仪器" class="prtGroupInstrBox">
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="添加" @click="addInstrDialog()"></vxe-button>
                  <vxe-table ref="instrTableRef" align="center" border class="mytable-scrollbar rptGroupInstrTable" :data="instrList" :loading="lloading" show-overflow keep-source>
                    <vxe-column type="seq" title="序号" width="40"></vxe-column>
                    <vxe-column field="instrCode" title="仪器代号"></vxe-column>
                    <vxe-column field="instrName" title="仪器名称"></vxe-column>
                    <vxe-column field="instrIdNo" title="仪器ID"></vxe-column>
                    <vxe-column field="instrClass" title="仪器类别"></vxe-column>
                    <vxe-column title="操作" fixed="right">
                      <template #default="{ row }">
                        <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click="deleteInstr(row)" class="spanIcon"></vxe-button>
                      </template>
                    </vxe-column>
                  </vxe-table>
                </el-tab-pane>
              </el-tabs>

              <el-dialog title="仪器" :show-close="false" v-model="showDialog" append-to-body width="1000px" :close-on-click-modal="false">
                <vxe-toolbar perfect>
                  <template #buttons>
                    <vxe-input style="width: 130px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getInstrs" @keyup="keyupInsrEnter" @search-click="getInstrs()"></vxe-input>
                    <vxe-button type="text" class="button-blue" content="查询" :loading="lloading" @click="getInstrs"></vxe-button>
                  </template>
                </vxe-toolbar>
                <div class="tableBody">
                  <vxe-table ref="instrTableRef" class="mytable-scrollbar" border="inner" align="left" height="500" :data="instrTableList" :loading="lloading" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                    <vxe-column type="checkbox" width="30px" align="center"></vxe-column>
                    <vxe-column type="seq" title="序号" width="30"></vxe-column>
                    <vxe-column field="instrCode" title="仪器代号"></vxe-column>
                    <vxe-column field="instrName" title="仪器名称"></vxe-column>
                    <vxe-column field="instrIdNo" title="仪器ID"></vxe-column>
                    <vxe-column field="instrClass" title="仪器类别"></vxe-column>
                  </vxe-table>
                </div>
                <div class="dialog-footer flex right justify-end" style="margin-top: 10px;">
                  <el-button type="primary" @click="saveBacthInstr()">确定</el-button>
                  <el-button @click="closeDialog()">取消</el-button>
                </div>
              </el-dialog>
            </Pane>
          </Splitpanes>
        </el-tab-pane>
        <el-tab-pane label="操作日志">
          <LogInfo requestUrl="/api/rptGroup"></LogInfo>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue';
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { IsEmpty, pageSizes } from '@/utils/common'; //导入工具函数
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息
import { funBdsJsResult } from '@/utils/Expression'; //函数公式
import LogInfo from '@/components/LogInfo.vue'; //操作日志
import { AppStore } from '@/stores/store';
import { isEmpty } from 'lodash';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();

const orgList = store.userInfo.orgList;
// 获取屏幕高度
let conHeight = ref((document.documentElement.clientHeight || document.body.clientHeight) - 148 + 'px');
// 获取屏幕宽度
let conWidth = ref(document.documentElement.clientWidth);
// 加载状态
let showLoading = ref(false); //左侧表格加载+上方刷新按钮+右侧表单+右侧详情
let showLoading1 = ref(false);
let saveLoading = ref(false); //保存
let rptGroupTable = ref(null); //报告单元表格
let rptGroupList: any = reactive([]); //报告单元列表数据

let instrList: any = reactive([]); //仪器列表数据
let searchForm = reactive({
  searchValue: ''
});
// 当前选中报告单元数据
let rptGroupInfo: any = reactive({
  id: '',
  rptGroupName: '',
  rptGroup: ''
});

let instrTableList: any = reactive([]); //弹出框List
// 模块对象
let modules: any = reactive([]);
let workGroupList: any = reactive([]); //字典表：指控规则类型
let currentUser = reactive({}); //当前报告单元
let form = reactive({
  id: null,
  rptGroupName: '',
  rptGroup: '',
  workGroup: '',
  businessType: '',
  remark1: '',
  remark2: '',
  remark3: '',
  rptGroupExplain: '',
  enable: '1', //是否启用
  inputCode: '',
  searchValue: '',
  orgId: store.userInfo.orgId,
  orgName: store.userInfo.orgName,
  seq: 0,
  poct: 1
});

let defaultProps = {
  children: 'children',
  label: 'name'
};

let businessTypeList: any = reactive([]);
let sltPurpose: any = ref({});

// 条数/页
const PageSizeList = [10, 50000, 100, 200, 500];

let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

let rptGroupFormRule: any = {
  rptGroupName: [
    {
      required: true,
      message: '请输入报告单元名称',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 256,
      message: '长度为1到256个字符',
      trigger: 'blur'
    },
    {
      message: '报告单元名只能为数字或英文字母',
      validator: proxy.validateUserName
    }
  ],
  rptGroup: [
    {
      required: true,
      message: '请输入报告单元编码',
      trigger: 'blur'
    }
    // {
    //   validator: validatePhoneTwo,
    //   trigger: 'blur'
    // }
  ]
};

// 页面加载时更新报告单元/字典
onMounted(() => {
  findRptGroupList1(); //加载报告单元列表
  getDictDetailList(); //加载字典
  getDictItemsList();
});

function handleOrgNodeClick(data: any) {
  form.orgId = data.id;
  form.orgName = data.name;
  handleSearch(form);
  const selectOrgRef: any = proxy.$refs['selectOrgRef'];
  selectOrgRef.blur();
}

//从词典获取所有的报告组
//获取界面字段
function getDictDetailList() {
  workGroupList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'JYGZZ' } })
    .then((res: any) => {
      workGroupList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['businessType'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const conKindType = dictTreeTypeItems.data.find((item) => item.code === 'businessType');
  businessTypeList.push(...conKindType.detailDataList);
  if (businessTypeList.length > 0) {
    form.businessType = businessTypeList[0].code;
  }
}

// 自动生成助记符
function autoInputCode() {
  form.inputCode = funBdsJsResult('firstPinYinFun', form.rptGroupName);
}

function getIsStaticStatusDesc(row) {
  if (row.enable == 1) {
    return '是';
  } else if (row.enable == 0) {
    return '否';
  }
}
function getIsStaticTagType(row) {
  if (row.enable == 1) {
    return 'success';
  } else if (row.enable == 0) {
    return 'danger';
  }
}

//点击每页数量
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findRptGroupList();
}

// 页面初次获取数据时默认选中第一个
function findRptGroupList1() {
  showLoading.value = true;
  rptGroupList.length = 0;
  const url = '/api/rptGroup/getRptGroupPoctList';
  proxy.$http
    .get(url, { params: { pageIndex: page.currentPage, pageSize: page.pageSize } })
    .then((res: any) => {
      //rptGroupList.push(...res.data.records);
      Object.assign(rptGroupList, res.data.records);
      page.totalResult = res.data.total;
      if (rptGroupList.length > 0) {
        rptGroupInfo.id = rptGroupList[0].id;
        rptGroupInfo.rptGroupName = rptGroupList[0].rptGroupName;
        rptGroupInfo.rptGroup = rptGroupList[0].rptGroup
        userRowClick({
          row: rptGroupList[0],
          rowIndex: 0
        });
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      showLoading.value = false;
      VxeMessage('1搜索报告单元列表失败', VxeNotifyType.error);
    });
}

//查询搜索报告单元列表
function findRptGroupList() {
  showLoading.value = true;
  rptGroupList.length = 0;
  const url = '/api/rptGroup/getRptGroupPoctList';
  proxy.$http
    .get(url, { params: { pageIndex: page.currentPage, pageSize: page.pageSize } })
    .then((res: any) => {
      rptGroupList.push(...res.data.records);
      page.totalResult = res.data.total;

      if (rptGroupList.length > 0) {
        const kn = rptGroupList.find((k) => k.id == sltPurpose.value.id);
        if (isEmpty(kn)) {
          rptGroupInfo.id = rptGroupList[0].id;
          rptGroupInfo.rptGroup = rptGroupList[0].rptGroup
          rptGroupInfo.rptGroupName = rptGroupList[0].rptGroupName;
          userRowClick({ row: rptGroupList[0] });
        } else {
          rptGroupInfo.id = kn.id;
          rptGroupInfo.rptGroup = kn.rptGroup
          rptGroupInfo.rptGroupName = kn.rptGroupName;
          userRowClick({ row: kn });
        }
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
  //showLoading.value = true;
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    handleSearch(form);
  }
}

// 查询/刷新
function handleSearch(row: any) {
  showLoading.value = true;
  rptGroupList.length = 0;
  const url = '/api/rptGroup/getRptGroupPoctList';
  proxy.$http
    .get(url, { params: { pageIndex: page.currentPage, pageSize: page.pageSize, keyWords: row.searchValue } })
    .then((res: any) => {
      rptGroupList.push(...res.data.records);
      page.totalResult = res.data.total;
      showLoading.value = false;
    })
    .catch((err: any) => {
      showLoading.value = false;
      VxeMessage('查询刷新失败', VxeNotifyType.error);
    });
}

// 重置
function resetForm(row: any) {
  if (isEmpty(row)) {
    clearForm();
    return;
  }
  form.rptGroupName = '';
  form.rptGroup = '';
  form.workGroup = '';
  form.businessType = '';
  form.remark1 = '';
  form.enable = '1';
  form.searchValue = '';
  form.remark2 = '';
  form.remark3 = '';
  form.inputCode = '';
  form.rptGroupExplain = '';
  form.orgId = store.userInfo.orgId;
  form.orgName = store.userInfo.orgName;
  form.seq = rptGroupList.length;
}

// 点击当前行// 行点击事件(需要调试)
function userRowClick({ row }: any) {
  if (isEmpty(row)) {
    currentUser = {} as any;
    return;
  }

  // let $Xtable = proxy.$refs.userTable;
  // $Xtable.setCurrentRow(row);
  getrptGroupById(row);
  getInstrById(row);
  currentUser = row;
  sltPurpose.value = row;
  (proxy.$refs.rptGroupTable as any).setCurrentRow(row);
  rptGroupInfo.id = row.id;
  rptGroupInfo.rptGroup = row.rptGroup;
  rptGroupInfo.rptGroupName = row.rptGroupName;
  modules.length = 0;
  //getSysUserAuthdetailsByRoleIds();
}

// 根据id获取报告单元单条信息
function getrptGroupById(rptGroup: any) {
  const url = '/api/rptGroup/findRptGroupSimple';
  proxy.$http
    .get(url, { params: { id: rptGroup.id } })
    .then((res: any) => {
      form.id = res.data.id;
      form.rptGroupName = res.data.rptGroupName;
      form.rptGroup = res.data.rptGroup;
      form.workGroup = res.data.workGroup;
      form.businessType = res.data.businessType;
      form.inputCode = res.data.inputCode;
      form.enable = res.data.enable;
      form.remark1 = res.data.remark1;
      form.searchValue = '';
      form.remark2 = res.data.remark2;
      form.remark3 = res.data.remark3;
      form.rptGroupExplain = res.data.rptGroupExplain;
      form.seq = res.data.seq;
      form.poct = res.data.poct;
    })
    .catch((err: any) => {
      // VxeMessage('获取用户员工报错', VxeNotifyType.error);
    });
}

// 根据id获取报告单元单条信息
function getInstrById(rptGroup: any) {
  instrList.length = 0;
  if (IsEmpty(rptGroup.rptGroup)) {
    return;
  }
  const url = '/api/rptGroup/findInstrByRptGroupId';
  proxy.$http
    .get(url, { params: { id: rptGroup.rptGroup } })
    .then((res: any) => {
      instrList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取用户员工报错', VxeNotifyType.error);
    });
}

// 新建报告单元
function addrptGroup() {
  clearForm();
  form.orgId = store.userInfo.orgId;
  form.orgName = store.userInfo.orgName;
  const lastRpt = rptGroupList[rptGroupList.length - 1];
  if (!isEmpty(lastRpt)) {
    if (lastRpt.seq != null) {
      form.seq = lastRpt.seq + 1;
    } else {
      form.seq = 0;
    }
  } else {
    form.seq = 0;
  }
  sltPurpose.value = {};
  (proxy.$refs.rptGroupTable as any).clearCurrentRow();
  modules.length = 0; //清空右侧盒子
}

// 保存
function save(formName: any) {
  let $el = proxy.$refs.rptGroupForm;
  if (!$el) return;
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const $form = proxy.$refs.rptGroupForm;
    saveLoading.value = true;
    if ($form) {
      const datas = $form.data;
      if (form.id == '' || form.id == null || form.id == undefined) {
        // 新增报告单元
        const url = '/api/rptGroup/addRptGroup';
        const rptGroup = {
          rptGroupName: form.rptGroupName,
          rptGroup: form.rptGroup,
          workGroup: form.workGroup,
          businessType: form.businessType,
          remark1: form.remark1,
          enable: form.enable,
          inputCode: form.inputCode,
          seq: form.seq,
          poct: form.poct
        };
        proxy.$http
          .post(url, rptGroup)
          .then((res: any) => {
            VxeMessage('新增报告单元成功', VxeNotifyType.success);
            clearForm();
            modules.length = 0;
            sltPurpose.value.id = res.data.id;
            findRptGroupList();
          })
          .catch((err: any) => {
            VxeMessage('新增报告单元失败', VxeNotifyType.error);
            findRptGroupList();
          });
      } else {
        // 修改报告单元
        const url = '/api/rptGroup/editRptGroup';
        const rptGroup = {
          id: form.id,
          rptGroupName: form.rptGroupName,
          rptGroup: form.rptGroup,
          workGroup: form.workGroup,
          businessType: form.businessType,
          remark1: form.remark1,
          enable: form.enable,
          remark2: form.remark2,
          remark3: form.remark3,
          rptGroupExplain: form.rptGroupExplain,
          inputCode: form.inputCode,
          seq: form.seq,
          poct: form.poct
        };
        proxy.$http
          .post(url, rptGroup)
          .then((res: any) => {
            VxeMessage('修改成功', VxeNotifyType.success);
            sltPurpose.value.id = res.data.id;
            findRptGroupList();
          })
          .catch((err: any) => {
            VxeMessage('修改失败', VxeNotifyType.error);
          });
      }
      saveLoading.value = false;
    }
  });
}

// 清空右侧表单
function clearForm() {
  form.id = null;
  form.rptGroupName = '';
  form.rptGroup = '';
  form.workGroup = '';
  form.businessType = '';
  form.remark1 = '';
  form.enable = '1';
  form.searchValue = '';
  form.remark2 = '';
  form.remark3 = '';
  form.rptGroupExplain = '';
  form.inputCode = '';
  form.seq = 0;
}

// 删除数据
function handleDelete() {
  const selectRows = (proxy.$refs.rptGroupTable as any).getCheckboxRecords();
  if (selectRows.length > 1) {
    VxeMessage('一次只可选择删除一条数据', VxeNotifyType.warning);
    return;
  }
  if (selectRows.length <= 0) {
    VxeMessage('请选择需要删除的报告单元', VxeNotifyType.warning);
    return;
  } else {
    proxy
      .$confirm('确定删除此条数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        selectRows.forEach(() => {
          const url = '/api/rptGroup/deleteRptGroupById';
          proxy.$http
            .post(url, selectRows[0])
            .then((res: any) => {
              if (res.status.code != 1) {
                VxeMessage('删除失败', VxeNotifyType.error);
              } else {
                VxeMessage('删除成功', VxeNotifyType.success);
                findRptGroupList();
                clearForm();
              }
            })
            .catch((err: any) => {
              proxy.$alert(err, '提示');
            });
        });
      });
  }
}

function getWorkGroupName(row) {
  // proxy.$nextTick(() => {
  if (workGroupList.length > 0) {
    const group = workGroupList.find((item) => item.code == row.workGroup);
    return group ? group.name : '';
  }
}

let lloading = ref(false); //加载状态
let showDialog = ref(false);
function addInstrDialog() {
  getInstrs();
  showDialog.value = true;
}

// 回车查询
function keyupInsrEnter(e: any) {
  if (e.$event.code == 'Enter') {
    getInstrs();
  }
}

// 查询没有关联到本报告单元的仪器
function getInstrs() {
  lloading.value = true;
  instrTableList.length = 0;
  const url = '/api/rptGroup/findInstrsByRptGroupId';
  proxy.$http
    .get(url, { params: { id: rptGroupInfo.id, keyWords: searchForm.searchValue } })
    .then((res: any) => {
      instrTableList.push(...res.data);
      lloading.value = false;
    })
    .catch((err: any) => {
      lloading.value = false;
      VxeMessage('查询仪器列表失败', VxeNotifyType.error);
    });
}

// 仪器列表隐藏
function closeDialog() {
  searchForm.searchValue = '';
  showDialog.value = false;
}

function saveBacthInstr() {
  const selectRows = (proxy.$refs.instrTableRef as any).getCheckboxRecords();
  if (selectRows.length > 0) {
    const addInstrList = [];
    const row = rptGroupTable.value?.getCurrentRecord();
    for (const sltRow of selectRows) {
      const addInstr = {
        id: sltRow.id,
        instrCode: sltRow.instrCode,
        instrName: sltRow.instrName,
        reportGroupId: rptGroupInfo.id,
        rptGroup: IsEmpty(row.rptGroup) ? null : row.rptGroup//rptGroupInfo.rptGroup
      };
      addInstrList.push(addInstr);
    }
    const data = { instrSetupList: addInstrList };
    const url = '/api/rptGroup/batchAddInstrList';
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        getInstrById(rptGroupInfo); // 获取检验仪器表格数据
        VxeMessage(res.status.msg, VxeNotifyType.success);
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  }
  closeDialog();
}

function deleteInstr(row: any) {
  proxy
    .$confirm('确定删除此仪器？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/rptGroup/deleteInstr';
      row.reportGroupId = '';
      proxy.$http.post(url, row).then((res: any) => {
        if (res.status.code === 1) {
          getInstrById(rptGroupInfo);
          VxeMessage('删除仪器成功', VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}
// 同步数据
async function pullPloyee() {
  showLoading1.value = true;
  const url = '/api/rptGroup/syncRptGroups';
  const params = {
    url: (window as any).apiUrl.VUE_APP_INTERFACE_URL + '/lisInterface/lisInterfacePost',
    code: 'GET_EMPLOYEE'
  };
  proxy.$http
    .get(url, { params: params })
    .then((res: any) => {
      showLoading1.value = false;
      findPloyeeList();
    })
    .catch((err: any) => {
      showLoading1.value = false;
      VxeMessage('同步失败', VxeNotifyType.error);
    });
}
</script>

<style lang="scss" scoped>
#labRptGroupPoct {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    :deep(.el-tabs) {
      height: 100%;

      .el-tabs__content {
        height: calc(100% - 39px);
        padding: 0;

        .el-tab-pane {
          height: 100%;
        }
      }
    }

    .area {
      background-color: $base-white;

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }

      .leftTable {
        height: calc(100% - 39px);

        // :deep(.vxe-table--render-wrapper) {
        //   height: 100%;

        //   .vxe-table--main-wrapper {
        //     height: 100%;

        //     .vxe-table--body-wrapper {
        //       height: calc(100% - 26px) !important;
        //     }
        //   }
        // }

        // :deep(.vxe-table--render-default) {
        //   height: calc(100% - 36px) !important;
        // }
      }

      .el-tabs--border-card {
        border: none;
        height: 100%;

        :deep(.el-tabs__content) {
          height: calc(100% - 39px - 20px);
          padding: 10px;

          .el-tab-pane {
            height: 100%;
          }
        }
      }

      // tab报告单元仪器

      .rptGroupInstrTable {
        height: calc(100% - 24px - 10px);
      }

      .el-radio {
        margin-right: 10px;
      }
    }
  }
}
</style>
